package com.lepu.app.fun.chat.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.app.utils.LoginUtil;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.main.LogUtilBase;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.fragment.ChatFragmentDoctor;
import com.lepu.app.fun.chat.fragment.ChatFragmentLectureRoom;
import com.lepu.app.fun.chat.fragment.ChatFragmentOnline;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.LectureUtil;
import com.lepu.app.fun.my.bean.BeanMyActivityDetail;
import com.lepu.pasm.R;

public class ChatMainActivity extends BaseFragmentActivity {

    public int mType = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_main_activity);

        registerHeadsetPlugReceiver();

        init();
    }

    @Override
    public void onDestroy() {
        LectureUtil.getInstance().clear();
        if (headsetPlugReceiver != null) {
            unregisterReceiver(headsetPlugReceiver);
        }
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
        finish(true);
    }

    /**
     * 初始化方法
     */
    private void init() {

        //每次进入聊天页面，检查是否连接openfire
        LoginUtil.loginOpenFire();

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.size() > 0) {
            mType = bundle.getInt("type");
        }

        if (mType == ChatConst.TYPE_ONLINE_CHAT_ONLINE) {
            //在线咨询
            ChatFragmentOnline fragmentChatOnline = new ChatFragmentOnline();
            fragmentTransaction.add(R.id.contentLayout, fragmentChatOnline);
            fragmentTransaction.commit();
        } else if (mType == ChatConst.TYPE_ONLINE_CHAT_DOCTOR_MY) {
            //私人医生
            ChatFragmentDoctor fragmentChatDoctor = new ChatFragmentDoctor();

            ChatSession chatSession = (ChatSession) getIntent().getSerializableExtra("ChatSession");
            String DoctorID = getIntent().getStringExtra("DoctorID");

            Bundle data = new Bundle();
            data.putSerializable("ChatSession", chatSession);
            data.putString("DoctorID", DoctorID);
            fragmentChatDoctor.setArguments(data);

            fragmentTransaction.add(R.id.contentLayout, fragmentChatDoctor);
            fragmentTransaction.commit();
        } else if (mType == ChatConst.TYPE_ONLINE_CHAT_LECTURE) {
            //讲座
            ChatFragmentLectureRoom fragmentChatLectureRoom = new ChatFragmentLectureRoom();

            BeanMyActivityDetail beanMyActivityDetail = (BeanMyActivityDetail) getIntent().getSerializableExtra("BeanMyActivityDetail");

            Bundle data = new Bundle();
            data.putSerializable("BeanMyActivityDetail", beanMyActivityDetail);
            fragmentChatLectureRoom.setArguments(data);

            fragmentTransaction.add(R.id.contentLayout, fragmentChatLectureRoom);
            fragmentTransaction.commit();
        }
    }

    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");
        registerReceiver(headsetPlugReceiver, intentFilter);

        // for bluetooth headset connection receiver
        IntentFilter bluetoothFilter = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(headsetPlugReceiver, bluetoothFilter);
    }

    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @SuppressWarnings("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                    if (BluetoothProfile.STATE_DISCONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
                        //Bluetooth headset is now disconnected
                        handleHeadsetDisconnected();
                    } else if (BluetoothProfile.STATE_CONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
                        handleHeadsetConnected();
                    }
                } else if ("android.intent.action.HEADSET_PLUG".equals(action)) {
                    if (intent.hasExtra("state")) {
                        if (intent.getIntExtra("state", 0) == 0) {
                            handleHeadsetDisconnected();
                        } else if (intent.getIntExtra("state", 0) == 1) {
                            handleHeadsetConnected();
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    };

    /***
     * 耳机链接上，把麦克风关闭
     */
    private void handleHeadsetConnected() {
        LogUtilBase.LogD(null,"耳机链接了");

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setSpeakerphoneOn(false);// 关闭扬声器
    }

    /**
     * 耳机拔了，打开麦克风
     */
    private void handleHeadsetDisconnected() {
        LogUtilBase.LogD(null,"耳机拔了");

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setSpeakerphoneOn(true);// 打开扬声器
    }
}
